﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using Microhard.WeixinMP.Models;
using Microhard.Core.Security;
using System.Configuration;
using Microhard.Core.DBUtility;
using Microhard.WeixinMP.Unities;
using Microhard.Permission.Models;
using Microhard.Framework.Extensions;
using Microhard.Permission.Interface;
using Microhard.Core;

namespace Microhard.Permission.MVCFilter.MVCFilter
{
    public class MVCFilterAtrForWeixinMP : ActionFilterAttribute, IMvcFilter
    {

        private string _errorMsg;
        private bool _isUsingOnAuth;

        public MVCFilterAtrForWeixinMP(bool isUsingOnAuth)
        {
            this.Order = -1;
            this._isUsingOnAuth = isUsingOnAuth;
        }

        public MVCFilterAtrForWeixinMP()
        {
            this.Order = -1;
        }

        public void RedirectToPage(ActionExecutingContext filterContext)
        {
            var vr = new ViewResult() { };
            vr.ViewName = "Error";
            vr.ViewData["Error"] = _errorMsg;
            filterContext.Result = vr;
            return;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //检查是否是从微信会话中发出来的服务请求
            if (!filterContext.HttpContext.IsWeixinClientRequest())
            {
                return;
            }
            filterContext.HttpContext.Items["isFromWeixin"] = true;
            object token = null;
            object userName = null;
            object model = null;
            if (filterContext.ActionParameters.ContainsKey("model"))
            {
                model = filterContext.ActionParameters["model"];
            }
            if (model == null)
            {
                if (filterContext.HttpContext.Request.HttpMethod == "GET")
                {
                    token = filterContext.HttpContext.Request.QueryString["WeixinToken"];
                    userName = filterContext.HttpContext.Request.QueryString["WeixinName"];
                }
                else
                {
                    token = filterContext.HttpContext.Request.Params["WeixinToken"];
                    userName = filterContext.HttpContext.Request.Params["WeixinName"];
                }

            }
            else
            {
                BasePermissionModel bmp = model as BasePermissionModel;
                userName = bmp.WeixinName;
                token = bmp.WeixinToken;
            }

            filterContext.HttpContext.Items["WeixinName"] = userName;
            filterContext.Controller.ViewData["WeixinName"] = userName;
            filterContext.Controller.ViewData["WeixinToken"] = token;

            //检查Token,username是否合法     
            if (token == null)
            {
                _errorMsg = "token为空，不符合安全要求";
                RedirectToPage(filterContext);
                return;
            }

            if (userName == null)
            {
                _errorMsg = "userName为空，不符合安全要求";
                RedirectToPage(filterContext);
                return;
            }

            var isAuthToken = SessionSecurity.IsAuthToken(token.ToString(), userName.ToString());
            if (!isAuthToken)
            {
                _errorMsg = "token匹配失败，不符合安全要求";
                RedirectToPage(filterContext);
                return;
            }
            else
            {
                var pageRequest = filterContext.RequestContext.HttpContext.Request;
                //如果使用微信onauth认证，则把用户信息载入到请求内存中
                if (_isUsingOnAuth)
                {
                    string code = pageRequest.QueryString["code"];
                    string state = pageRequest.QueryString["state"];
                    string strcmpid = pageRequest.QueryString["cmpID"];
                    filterContext.Controller.ViewData["cmpID"] = strcmpid;

                    Guid companyID = Guid.Empty;
                    string companyName;
                    Guid cmpid = Guid.Parse(strcmpid);
                    var info = WeixinTools.OnAuthGetUserInfo(cmpid, code, state, out companyID, out companyName);
                    Log.Info("OnAuth", "code:" + code + " state:" + state + " cmpID:" + cmpid);
                    if (!string.IsNullOrEmpty(info.nickname) && !string.IsNullOrEmpty(info.openid))
                    {
                        info.BelongCompanyID = companyID;
                        info.BelongCompanyName = companyName;

                        if (filterContext.ActionParameters.Keys.Contains("WXUserInfo"))
                        {
                            filterContext.ActionParameters["WXUserInfo"] = info;
                        }
                    }
                    else
                    {
                        _errorMsg = "使用OnAuth获取用户信息失败";
                        RedirectToPage(filterContext);
                        return;
                    }
                }
            }

        }
    }
}
